package com.likai.jarscms.controller;

import com.likai.jarscms.pojo.Manager;
import com.likai.jarscms.service.IManagerService;
import com.likai.jarscms.utils.AnswerJson;
import com.likai.jarscms.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by likai on 2018/10/14.
 */
@Controller
@RequestMapping(value = "/user")
public class ManagerController {

    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(ManagerController.class);

    @Autowired
    @Qualifier("managerService")
    private IManagerService managerService ;

    @RequestMapping(value = "/login",method = {RequestMethod.GET,RequestMethod.POST})
    public String login(
            Manager manager,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken token =
                new UsernamePasswordToken(manager.getUsername(), Md5Util.md5(manager.getPassword(), manager.getUsername()));

        try {
            subject.login(token);
            return "redirect:/admin/main" ;
        } catch (Exception e) {
            LOGGER.error("Exception",e);
            request.setAttribute("errorInfo","用户名密码错误");
            return "/login" ;
        }
    }
}
